import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '../utils/auth'
import store from '../store'
import setting from '../setting'
import Login from '../pages/Login/index.vue'

Vue.use(VueRouter)

// 新建路由时，元数据中lock参数必须设置
const routes = [
  {
    path: '/',
    redirect: { name: setting.publicIndexPage }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { title: '登录', lock: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import(/* webpackChunkName: 'home' */ '../pages/Home/index.vue'),
    meta: { title: '首页', lock: true },
    children: [
      {
        path: '/Monitor_project',
        name: 'Monitor_project',
        component: () => import(/* webpackChunkName: 'project' */ '../pages/Monitor_project/index.vue'),
        meta: { title: '工程列表', lock: true }
      },
      {
        path: '/Tunnel_manage',
        name: 'Tunnel_manage',
        component: () => import(/* webpackChunkName: 'project' */ '../pages/Tunnel_manage/index.vue'),
        meta: { title: '隧道管理', lock: true }
      },
      {
        path: '/staff',
        name: 'Staff',
        component: () => import(/* webpackChunkName: 'staff' */ '../pages/Staff/index.vue'),
        meta: { title: '员工列表', lock: true }
      },
      {
        path: '/company',
        name: 'company',
        component: () => import(/* webpackChunkName: 'staff' */ '../pages/Company/index.vue'),
        meta: { title: '公司列表', lock: true }
      },
      {
        path: '/user',
        name: 'User',
        component: () => import(/* webpackChunkName: 'user' */ '../pages/User/index.vue'),
        meta: { title: '个人信息', lock: true }
      },
      {
        path: '/Monitor_point',
        name: 'Monitor_point',
        component: () => import(/* webpackChunkName: 'work_report' */ '../pages/Monitor_point/index.vue'),
        meta: { title: '点位沉降记录', lock: true }
      },
      {
        path: '/Monitor_log',
        name: 'Monitor_log',
        component: () => import(/* webpackChunkName: 'work_report' */ '../pages/Monitor_log/index.vue'),
        meta: { title: '监控点', lock: true }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = `${to.meta.title} - ${setting.appName}`
  } else {
    document.title = `${setting.appName}`
  }
  if (!to.meta.lock) {
    next()
  } else {
    // 判断是否首次登录
    if (getToken() === undefined && store.state.userinfo !== null) {
      next()
    } else {
      if (getToken() === undefined) {
        next({ name: setting.publicIndexPage })
      } else {
        next()
      }
    }
  }
})

export default router
